import { createSlice } from '@reduxjs/toolkit'

const cartSlice = createSlice({
    name:'cartSlice',
    initialState:{
        cartlist:JSON.parse(localStorage.getItem('cartlist') || '[]'),
    },
    reducers:{
        // 添加购物车
        addCart(state,{payload}){
            const index = state.cartlist.findIndex((item: any) => item.restorativesid === payload.restorativesid);
            if (index !== -1) {
                // 如果商品已存在，则增加数量
                state.cartlist[index].count += 1;
            } else {
                // 如果商品不存在，则添加新商品并设置数量为 1
                state.cartlist.push({ ...payload, count: 1 ,status:false});
            }
            localStorage.setItem('cartlist',JSON.stringify(state.cartlist))
        },
        // 单选
        dan(state,{payload}){
             const index = state.cartlist.findIndex((item: any) => item.restorativesid === payload.restorativesid);
             if (index !== -1) {
                 state.cartlist[index].status = !state.cartlist[index].status;
            } 
            localStorage.setItem('cartlist',JSON.stringify(state.cartlist))
        },
        // 全选
        quan(state,{payload}){
            state.cartlist.forEach((item:any)=>{
                item.status = payload
            })
             localStorage.setItem('cartlist',JSON.stringify(state.cartlist))
        },
        // 数量变化
        numchange(state,{payload}){
             const index = state.cartlist.findIndex((item: any) => item.restorativesid === payload.restorativesid);
              if (index !== -1) {  // 这里需要判断是否找到了对应的商品
                state.cartlist[index].count = payload.count;  // 更新数量
         }
             localStorage.setItem('cartlist',JSON.stringify(state.cartlist))
        },
        // 删除
        del(state,{payload}){
            state.cartlist = state.cartlist.filter((item:any)=>item.restorativesid !== payload.restorativesid)
             localStorage.setItem('cartlist',JSON.stringify(state.cartlist))
        },
        // 全选删除
        alldel(state, { payload }) {
            state.cartlist = state.cartlist.filter((item:any) =>!payload.restorativesids.includes(item.restorativesid));
            localStorage.setItem('cartlist', JSON.stringify(state.cartlist));
        }
    }
})

export const {addCart,dan,quan,numchange,del,alldel} = cartSlice.actions
export default cartSlice.reducer